import UIKit
public typealias TestPaperDetailsSelectBlock = (_ subjectId:NSInteger, _ answerList: NSMutableArray ,_ access_key:NSString ,_ msg:NSString) -> Void

public typealias SubmitTestPaperBlock = (_ access_key:NSString ,_ ID:NSInteger) -> Void

public class TalkfunTestPaperDetails: UIView ,UICollectionViewDelegate, UICollectionViewDataSource ,UICollectionViewDelegateFlowLayout,TalkfunTestPaperDetailsCellDelegate {
    
    @objc public var testPaperDetailsSelectBlock:TestPaperDetailsSelectBlock?
    //提交试卷
    @objc public var submitTestPaperBlock:SubmitTestPaperBlock?
    
    @objc public var dataList:NSMutableArray = NSMutableArray.init()
 
    var isAddFillet: Bool = false
    //头部
    let headView = TalkfunTestPaperDetailsHeadView.init()
    //尾部  分布的
    let tailView = TalkfunTestPaperDetailsTailView.init()
    //尾部 一页的
    let cellSubmit = TalkfunTestPaperDetailsSubmitCell.init()
    
    @objc public var model:TFExaminationDetail?
    @objc public var YEqualsHigh = false
    
    var access_key:NSString = ""
    //试卷列表
    @objc public let collectionView = UICollectionView.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0), collectionViewLayout: UICollectionViewFlowLayout())
    let TalkfunTestPaperDetailsCell_ID = "TalkfunTestPaperDetailsCell_ID"
    let TalkfunTestPaperDetailsSubmitCell_ID = "TalkfunTestPaperDetailsSubmitCell_ID"
    //题号卡
    var questionNumberCard = TalkfunQuestionNumberCard()
    var currentPage = 1
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.headView.closeOrBack.addTarget(self, action: #selector(self.closeOrBackClick), for: UIControl.Event.touchUpInside)
        self.headView.more.addTarget(self, action: #selector(self.headViewMoreClick), for: UIControl.Event.touchUpInside)
        self.tailView.more.addTarget(self, action: #selector(self.tailViewMoreClick), for: UIControl.Event.touchUpInside)
        
        self.backgroundColor = UIColor(red: 0.96, green: 0.96, blue: 0.98, alpha: 1)

        self.addSubview(self.headView)
        self.headView.backgroundColor = UIColor(red: 0.96, green: 0.96, blue: 0.97, alpha: 1)
        self.addSubview(self.tailView)
        self.tailView.isHidden = true
        
        self.cellSubmit.submit.addTarget(self, action: #selector(self.submitClick), for: UIControl.Event.touchUpInside)
        self.cellSubmit.isHidden = true
        self.addSubview(self.cellSubmit)
        
        self.tailView.previousBtn.addTarget(self, action: #selector(self.previousClick), for: UIControl.Event.touchUpInside)
        self.tailView.nextBtn.addTarget(self, action: #selector(self.nextClick), for: UIControl.Event.touchUpInside)
        
  
        if #available(iOS 11.0, *) {
            self.collectionView.contentInsetAdjustmentBehavior = .never
            }
        self.addSubview(self.collectionView)
        self.collectionView.clipsToBounds = true
        self.collectionView.dataSource = self
        self.collectionView.delegate = self
        self.collectionView.register(TalkfunTestPaperDetailsCell.self, forCellWithReuseIdentifier:TalkfunTestPaperDetailsCell_ID)
        self.collectionView.register(TalkfunTestPaperDetailsSubmitCell.self, forCellWithReuseIdentifier:TalkfunTestPaperDetailsSubmitCell_ID)
        
        self.collectionView.reloadData()
        self.collectionView.backgroundColor = UIColor.clear
        self.questionNumberCard.didSelectBlock =  {[weak self](rom) in
           
            let inx = rom as NSInteger;
            let scrollIndexPath = NSIndexPath.init(row: inx, section: 0)
            self?.collectionView.scrollToItem(at: scrollIndexPath as IndexPath, at: UICollectionView.ScrollPosition.top, animated: true)

            
            self!.tailViewMore(currentPage: inx + 1 )
            
            guard self != nil else {
                return
            }
            
        }


    }

    public override func layoutSubviews() {
        super.layoutSubviews()
        
        var reloadData = false
        if (self.isAddFillet == false || self.collectionView.frame.width != self.frame.width)
        {
            let maskPath = UIBezierPath.init(roundedRect: self.bounds, byRoundingCorners:[UIRectCorner.topRight,UIRectCorner.topLeft], cornerRadii: CGSize(width: 10, height: 10))
            
            let  maskLayer = CAShapeLayer()
            maskLayer.frame = self.bounds
            maskLayer.path = maskPath.cgPath
            
            self.layer.mask = maskLayer
            self.isAddFillet = true
            reloadData = true
        }

        self.collectionView.frame = self.getCollectionViewFrame()
        if reloadData {
            //因为数据源的数量不一样了 ,所以要更新一下
            self.collectionView.reloadData()

            if (self.currentPage < self.dataList.count) {
                let scrollIndexPath = NSIndexPath.init(row: self.currentPage, section: 0)
                self.collectionView.scrollToItem(at: scrollIndexPath as IndexPath, at: UICollectionView.ScrollPosition.top, animated: true)
            }
           
        }
        
        if self.questionNumberCard.frame.width == 0 {
            self.questionNumberCard.frame = CGRect(x: 0, y: self.frame.height, width: self.frame.width, height: self.frame.height)
        }else
        {
            var questionNumberCardY = 0.0
            if self.questionNumberCard.frame.origin.y != 0 {
                questionNumberCardY = self.frame.height
            }
            self.questionNumberCard.frame = CGRect(x: 0, y: questionNumberCardY, width: self.frame.width, height: self.frame.height)
        }
        

    }
    @objc public func refreshUI()
    {
        self.dataList.removeAllObjects()
        self.collectionView.reloadData()
    }
    @objc public func reload(isShow:Bool)
    {
        if (isShow && (self.superview != nil))
        {
            //bringSubviewToFront
            if ((self.superview) != nil) {
                self.superview?.bringSubviewToFront(self)
            }
            
            self.YEqualsHigh = false
            UIView.animate(withDuration: 0.5) {
                self.frame = CGRect(x: self.frame.origin.x, y:0, width: self.frame.size.width, height: self.frame.size.height)
                self.refreshUI()
            }
           
        }
    }
    //添加详情模型
    @objc public func addData(_ model:TFExaminationDetail )
    {
        self.model = nil
        self.model = model;
        //问卷
        if self.model!.subjectExamineInfo.type == TFExaminationTypeTable {
            self.headView.countdown.isHidden = true
        }
        self.dataList.removeAllObjects()
        self.dataList = NSMutableArray.init(array:model.subjectDetailList)
        
        let type = self.model!.subjectExamineInfo.type as TFExaminationType
        
        self.questionNumberCard.addData(list: model.subjectDetailList as NSArray, type: type)
            
        
        var inx = ""
        //2已批阅
        if (model.subjectExamineAnswerInfo.answerStatus == TalkfunAnswerStatusApproved || model.subjectExamineInfo.isEndOfTestPaper == true)
        {
           
            self.questionTitle(count: 99)
            self.headView.countdown.isHidden = true
            
            let count = NSString(format: "%li", model.subjectExamineAnswerInfo.score )
            
             inx = "答对" + (count as String) + "题"

            self.headView.more.setImage(UIImage.init(named:"tf_icon_test"), for: UIControl.State.normal)
            self.headView.more.setImage(UIImage.init(named:"tf_icon_test"), for: UIControl.State.highlighted)
            
            if(self.model!.subjectExamineInfo.pageType == TalkfunQuestionnairePageStatusOnePage)
                
            {
                self.cellSubmit.submit.setTitle(inx, for: UIControl.State.normal)
                
                let answerCount = 1 as NSInteger
                let coutStr = NSString(format: "%i", answerCount)
                
                 inx = coutStr as String + "/" + (NSString(format: "%i", self.questionNumberCard.list.count) as String)
                
                
                self.headView.more.setImage(UIImage.init(named: "HTLive.bundle/TFMore"), for: UIControl.State.normal)
                self.headView.more.setImage(UIImage.init(named: "HTLive.bundle/TFMore"), for: UIControl.State.highlighted)
              
            }
            
            
        }else if (model.subjectExamineAnswerInfo.answerStatus == TalkfunAnswerStatusSubmitted)
        {
            inx = "已交卷"
            self.headView.more.setImage(UIImage.init(named: "HTLive.bundle/TFicon_test"), for: UIControl.State.normal)
            self.headView.more.setImage(UIImage.init(named: "HTLive.bundle/TFicon_test"), for: UIControl.State.highlighted)
            
         
        }else if (model.subjectExamineAnswerInfo.answerStatus == TalkfunAnswerStatusParticipated)
        {
            //未提交
            let answerCount = 1 as NSInteger
            let coutStr = NSString(format: "%i", answerCount)
            
             inx = coutStr as String + "/" + (NSString(format: "%i", self.questionNumberCard.list.count) as String)
            //不是问卷才能显示
            if self.model!.subjectExamineInfo.type != TFExaminationTypeTable {
               self.headView.countdown.isHidden = false
            }
            if(self.model!.subjectExamineInfo.pageType == TalkfunQuestionnairePageStatusOnePage)
            {
                //用于提交  60.0 + 34.0 的尾部
//                self.dataList.add(TalkfunSubjectExamineDetail.init())
                self.headView.more.setImage(UIImage.init(named: "HTLive.bundle/TFMore"), for: UIControl.State.normal)
                self.headView.more.setImage(UIImage.init(named: "HTLive.bundle/TFMore"), for: UIControl.State.highlighted)
            }else
            {
                
                self.headView.more.setImage(UIImage.init(named: "HTLive.bundle/TFicon_test"), for: UIControl.State.normal)
                self.headView.more.setImage(UIImage.init(named: "HTLive.bundle/TFicon_test"), for: UIControl.State.highlighted)
                
                self.tailView.more.setImage(UIImage.init(named: "HTLive.bundle/TFMore"), for: UIControl.State.normal)
                self.tailView.more.setImage(UIImage.init(named: "HTLive.bundle/TFMore"), for: UIControl.State.highlighted)
                inx = "交卷"
            }
        
            self.cellSubmit.submit.setTitle("交卷", for: UIControl.State.normal)
            
        }
        //不是问卷才创建定时器
        if self.model!.subjectExamineInfo.type != TFExaminationTypeTable {
        self.timerInvalidate()
        
        self.headView.timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(setRtxt), userInfo: nil, repeats: true)
            RunLoop.main.add(self.headView.timer! , forMode: RunLoop.Mode.default)
        
        self.headView.timer.fire()
            
        }
        let status = self.model!.subjectExamineInfo.pageType as TalkfunQuestionnairePageStatus
        self.headView.moreTitle(title: inx as NSString,status:status )
        
        self.tailViewMore(currentPage: 1)
        
        self.addSubview(self.questionNumberCard)
        
        self.collectionView.setContentOffset(CGPoint(x: 0, y: 0), animated:false)
        //因为数据源的数量不一样了 ,所以要更新一下
        self.collectionView.reloadData()
        //刷新一下cell
        self.collectionView.collectionViewLayout.invalidateLayout()
        self.collectionView.layoutIfNeeded()
        //  1.分页式
        if(model.subjectExamineInfo.pageType == TalkfunQuestionnairePageStatusPagination)
        {
            let layout = UICollectionViewFlowLayout()
                layout.minimumLineSpacing = 0
                layout.minimumInteritemSpacing = 0
                layout.scrollDirection = .horizontal

            self.collectionView.collectionViewLayout = layout
            self.collectionView.isPagingEnabled = true
            self.collectionView.isScrollEnabled = false
          
        }else if(model.subjectExamineInfo.pageType == TalkfunQuestionnairePageStatusOnePage)
        {
            //2.一页式
            let layout = UICollectionViewFlowLayout()
                layout.minimumLineSpacing = 16
                layout.minimumInteritemSpacing = 0
            layout.scrollDirection = .vertical
            self.collectionView.collectionViewLayout = layout
            self.collectionView.isPagingEnabled = false
            self.collectionView.isScrollEnabled = true
        }
        
        self.collectionView.reloadData()
        self.turnPages()
    }
    
    //TODO: 数据源
    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return self.dataList.count
    }
    //TODO: UICollectionViewCell的创建
    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
 
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: TalkfunTestPaperDetailsCell_ID, for: indexPath) as! TalkfunTestPaperDetailsCell
        
            cell.delegate = self
            cell.tag = indexPath.row
            if (indexPath.row < self.dataList.count) {
                cell.collectionViewH = self.getCollectionViewFrame().height
                
                if (self.model!.subjectExamineInfo.pageType == TalkfunQuestionnairePageStatusOnePage) {
                    cell.pageType = TalkfunQuestionnairePageStatusOnePage
                }else
                {
                    cell.pageType = TalkfunQuestionnairePageStatusPagination
                }
              
                let model = self.dataList[indexPath.row] as! TalkfunSubjectExamineDetail
                let inx = indexPath.row + 1
                cell.textLabelAttrString(text: NSString(format: "第%i题", inx))
                cell.isEndOfTestPaper = self.model!.subjectExamineInfo.isEndOfTestPaper
                
                cell.subjectExamineInfoType =  self.model!.subjectExamineInfo.type
                cell.model = model
                cell.webViewHeightBlock = {[weak self](height) in
                    if(cell.model?.titleWebViewHeight != height)
                    {
                       cell.model?.titleWebViewHeight = height
                    let positon = IndexPath(row: cell.tag, section: 0)
                        self!.collectionView.reloadItems(at: [positon])
                    }
                    
                    guard self != nil else {
                       return
                   }
                }
                cell.analysisHeightBlock = {[weak self](height) in
                    if(cell.model?.analysisWebViewHeight != height)
                    {
                        cell.model?.analysisWebViewHeight = height
                        self?.collectionView.reloadData()
                    }
                   
                    guard self != nil else {
                       return
                   }
                }
                cell.testPaperDetailsSelectBlock = {[weak self](subjectId ,answer,access_key,msg) in
                
                    let access_key = self?.model?.access.access_key
                if self?.testPaperDetailsSelectBlock != nil {
                    self!.testPaperDetailsSelectBlock!( subjectId,answer ,access_key! as NSString ,msg)
                }
                    
                }
                
                cell.selectAndStateBlock = {[weak self](rom ,State) in
                    
                    self!.questionNumberCard.selectedNumberCard(inx: rom,state: State)

                    var count = 0
                    for obj in self!.questionNumberCard.list {
                        
                        let num = obj as! TalkfunQuestionNumberModel
                       
                        if (num.selected)
                        {
                            count = count + 1
                        }
                    }
                    self!.addSubview(self!.questionNumberCard)
                    
                    guard self != nil else {
                        return
                    }
                    
                }
                
                
                //填写题 数据提交
                cell.testPaperDetailslReply.replyBlock = {[weak self]() in
                    
                    let access_key = self?.model?.access.access_key
                    
                    let subjectId = cell.model!.subjectId as NSInteger
                    
                    let answerList = NSMutableArray()
                    
                    for i in stride(from: 0, to: cell.model!.subjectAnswerList.count ,by: 1) {
                        let answer = cell.model!.subjectAnswerList[i] as! TalkfunSubjectAnswer
                        
                        answerList.add(answer.fillInTheBlank as Any)
                    }
                    
                    
                if self?.testPaperDetailsSelectBlock != nil {
                    self!.testPaperDetailsSelectBlock!( subjectId,answerList ,access_key! as NSString ,"")
                }
                    guard self != nil else {
                        return
                    }
                }
                
                
                //简答题 数据提交
                cell.testPaperDetailslReply.briefReplyBlock = {[weak self](msg:NSString) in
                    
                    let access_key = self?.model?.access.access_key
                    
                    let subjectId = cell.model!.subjectId as NSInteger

                    let answerList = NSMutableArray()

                    answerList.add(msg)
                    
                    
                    let str:NSString = msg
                    
                    var isSelected:Bool = false
                    if str.length > 0 {
                        isSelected = true
                    }
                    self!.questionNumberCard.selectedNumberCard(inx: cell.tag,state: isSelected)
                if self?.testPaperDetailsSelectBlock != nil {
                    self!.testPaperDetailsSelectBlock!( subjectId,answerList ,access_key! as NSString ,msg)
                }
                    guard self != nil else {
                        return
                    }
                }
                
                
                
                
            }
            
            return cell

       
    }
    //TODO: UICollectionViewCell高度
    public func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                        sizeForItemAt indexPath: IndexPath) -> CGSize
    {
       
        
        
        let cellW2 = self.frame.width
        //- 12.0 - 12.0
        if (indexPath.row >= self.dataList.count) {
            return CGSize(width: cellW2, height: 0)
        }

            
            //单个主题模型
            let model2 = self.dataList[indexPath.row] as! TalkfunSubjectExamineDetail
        
            var textLabelW = cellW2 - 16.0 - 16.0 - 12.0 - 12.0 - 12.0 - 12.0
            //填空列表
        if (model2.subjectInfo.type == TalkfunTopicTypeStuff && self.model!.subjectExamineInfo.isEndOfTestPaper == true)
            {
                textLabelW = textLabelW - 64.0 - 16.0
            }
         
            // 填空的cell
            var optionsListHight = 54.0 + 15.0 + (model2.titleWebViewHeight) + TalkfunTestPaperDetails.getOptionsListHightFilling(model: model2)
      

          //不是填空题4 或者 课程结束了
        optionsListHight = optionsListHight +  TalkfunTestPaperDetails.getOptionHeight(model2: model2, isEndOfTestPaper: self.model!.subjectExamineInfo.isEndOfTestPaper, textLabelW: textLabelW)
        
    
        //TFExaminationTypeTestPaper 随堂考
        if (self.model!.subjectExamineInfo.isEndOfTestPaper == true && self.model!.subjectExamineInfo.type == TFExaminationTypeTestPaper)
            {

                //5.0 是与上面的间距  答案:a.c
                var AnswerHight = (23 + 10.0)
                //4填空题
            if (model2.subjectInfo.type == TalkfunTopicTypeStuff){
                    AnswerHight = 0
                }

                //解析 ( 10.0 + 23)
                let analysisWebViewHeight = 10.0 + model2.analysisWebViewHeight

                optionsListHight = optionsListHight + AnswerHight + analysisWebViewHeight


            }
        
        if self.model!.subjectExamineInfo.type == TFExaminationTypeTestPaper {
            //用户未选择选项 = 未作答 &&考试已结  59.5
            if((model2.subjectExamineAnswerDetailInfo.answer.count) == 0 && self.model!.subjectExamineInfo.isEndOfTestPaper == true)
            {
                optionsListHight = optionsListHight + 59.5
            }else if(self.model!.subjectExamineInfo.isEndOfTestPaper == true)
            {
                optionsListHight = optionsListHight + 20.0
            }
        }
           
            
            model2.cellHeight = optionsListHight
           //一页
        if (self.model!.subjectExamineInfo.pageType == TalkfunQuestionnairePageStatusOnePage) {
                var spacing = 0.0
            if self.model!.subjectExamineInfo.isEndOfTestPaper == true {
                if self.model!.subjectExamineInfo.type == TFExaminationTypeTestPaper {
                        spacing = 36.0
                    }
                   
                }
                return CGSize(width: cellW2, height: optionsListHight + spacing )
            }else
            {
                //分页
             
                return CGSize(width: cellW2, height: self.getCollectionViewFrame().height  )
            }
            
      
    }
    //填写 (也有可以是简答)
    @objc static func getOptionsListHightFilling(model:TalkfunSubjectExamineDetail) ->CGFloat
    
    {
        var optionsListHight:CGFloat = 0
        
        //题目中的选项list 选项: A  B C D
        let optionsList = model.subjectAnswerList as NSArray
        /**1单选题、2多选题、3判断题、4填空题、5简答题*/
        if (model.subjectInfo.type == TalkfunTopicTypeStuff) {
            
            let msgH = optionsList.count * 44
          
            let spacing = (optionsList.count - 1) * 15
             
            let testPaperDetailslReplyH = Double(msgH + spacing)
            
            //400.0
            optionsListHight = optionsListHight + testPaperDetailslReplyH
        }
        else if (model.subjectInfo.type == TalkfunTopicTypeShortAnswer) {
             //简答题 15 间距
            optionsListHight = optionsListHight + 96.5 + 15
        }
        
        return optionsListHight
    }
    
    //选项的高度
    @objc static func getOptionHeight(model2:TalkfunSubjectExamineDetail,isEndOfTestPaper:Bool,textLabelW:CGFloat) ->CGFloat
    {
        //题目中的选项list 选项: A  B C D
        let optionsList = model2.subjectAnswerList as NSArray
        
        
        var optionsListHight:CGFloat = 0
        
        //不是填空题4 或者 课程结束了
        if (model2.subjectInfo.type != TalkfunTopicTypeStuff || isEndOfTestPaper == true )
            
        {

            for obj in  optionsList {
                let model = obj as! TalkfunSubjectAnswer

                 let prefix = TalkfunSharedTools.asciiBytesToString(inx: 1) + "."
                let msg = prefix + model.answer
                
  
                let sizeLabelHightAndSpacing = TalkfunTestPaperDetails.getsizeLabelHightAndSpacing(msg: msg as NSString, textLabelW: textLabelW, model: model2 )
                 
                var spacing = 15.0
                if (model2.subjectInfo.type == TalkfunTopicTypeStuff )
                {
                    spacing = 5.0
                }
                 optionsListHight = optionsListHight + sizeLabelHightAndSpacing + spacing
                
               
             }
        
        }
        
        return optionsListHight
    }
    
    @objc static func getsizeLabelHightAndSpacing(msg:NSString,textLabelW:CGFloat ,model:TalkfunSubjectExamineDetail )->CGFloat
    {
        let titleAttrString = NSMutableAttributedString(string:msg as String)
        let sizeLabel = TalkfunSharedTools.getSizeLabel(labelString: titleAttrString, labelWidth: textLabelW , labelfont: UIFont(name: "PingFang SC", size: 16)! )
        // 对的 104.5
       let sizeLabelHightAndSpacing = (sizeLabel.height + TalkfunSharedTools.getOptionsCellLineSpacing(model: model))
        
        return sizeLabelHightAndSpacing
    }
    //TODO: 點選 cell 後執行的動作
    public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        

            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: TalkfunTestPaperDetailsCell_ID, for: indexPath) as! TalkfunTestPaperDetailsCell
            
            
            cell.getgetInputValue()
          

    }
    
    //scrollViewDidScroll 人为拖拽
    public func scrollViewDidScroll(_ scrollView: UIScrollView) {
        //&& self.model!.subjectExamineInfo?.isEndOfTestPaper == false
        if ((self.model) != nil ) {
            if(self.model!.subjectExamineInfo.pageType == TalkfunQuestionnairePageStatusOnePage)

            {

                let p = CGPoint(x: 0, y: scrollView.contentOffset.y + (scrollView.frame.height / 2.0))
                
                let indexPath =  self.collectionView.indexPathForItem(at: p)
                if ((indexPath) != nil) {
                    self.headViewMore(currentPage: indexPath!.row + 1)
                }
                
            }
        }
       
    }
    //滚动完毕就会调用（如果不是人为拖拽scrollView导致滚动完毕，才会调用这个方法）
    public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        
     
        
    }
    //滚动完毕后就会调用（如果是人为拖拽scrollView导致滚动完毕，才会调用这个方法）
    public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {

        
    }
    @objc func setRtxt() {
     
        if (self.model!.subjectExamineInfo.endTime >= TalkfunSharedTools.getCurrentDateString()  )
            
        {
            //时差
            let timeDifference = self.model!.subjectExamineInfo.endTime - TalkfunSharedTools.getCurrentDateString()
            let countdownStr = TalkfunSharedTools.timeDifference(endTime: self.model!.subjectExamineInfo.endTime)
            self.headView.openCountdown(time: countdownStr)
            if( timeDifference == 0)
            {
                self.headView.countdown.isHidden = true
                self.timerInvalidate()
            }
            //结束定时器
            if (self.model!.subjectExamineInfo.endTime == TalkfunSharedTools.getCurrentDateString()  )
            {
                self.timerInvalidate()
            }
        }
         
    }
    func getCollectionViewFrame()->CGRect
    {
         let headViewHeight = 54.0
        
        self.headView.frame = CGRect(x: 0.0, y: 0.0, width: self.frame.width, height: headViewHeight)
        
        var tailViewH = 0.0
        if ((self.model) != nil) {
            //  1.分页式
            if(self.model!.subjectExamineInfo.pageType == TalkfunQuestionnairePageStatusPagination)
            {
                tailViewH = 60.0 + 34.0
                self.tailView.isHidden = false
                self.cellSubmit.isHidden = true
            }else if(self.model!.subjectExamineInfo.pageType == TalkfunQuestionnairePageStatusOnePage  )
            {
             
                
                //参与状态 0未提交、1已提交、2已批阅
                //未提交
                if ((self.model!.subjectExamineAnswerInfo.answerStatus == TalkfunAnswerStatusParticipated && self.model!.subjectExamineInfo.isEndOfTestPaper == false) || self.model!.subjectExamineAnswerInfo.answerStatus == TalkfunAnswerStatusApproved) {
                    tailViewH = 60.0 + 34.0
                    
                    //2已批阅 的表单
                    if (self.model!.subjectExamineInfo.type == TFExaminationTypeTable && self.model!.subjectExamineAnswerInfo.answerStatus == TalkfunAnswerStatusApproved) {
                        tailViewH = 0
                    }
                    self.cellSubmit.isHidden = false
                    self.tailView.isHidden = true
                }else if (self.model!.subjectExamineAnswerInfo.answerStatus == TalkfunAnswerStatusSubmitted)
                {
                    
                }
            }
            else
            {
                self.tailView.isHidden = true
                self.cellSubmit.isHidden = true
            }
        }
       
        
        self.tailView.frame = CGRect(x: 0.0, y: self.frame.height - tailViewH, width: self.frame.width, height: tailViewH)

        self.cellSubmit.frame = CGRect(x: 0.0, y: self.frame.height - tailViewH, width: self.frame.width, height: tailViewH)
        
 
        let collectionViewW = self.frame.size.width
        let collectionViewH = self.frame.size.height - headViewHeight - tailViewH
          
        let collectionViewFrame = CGRect(x: 0, y: headViewHeight, width: collectionViewW , height: collectionViewH)
        return collectionViewFrame
    }

    func isUnsubmitted(indexPath: IndexPath)->Bool
    {
        var unsubmitted = false
        if (self.model!.subjectExamineAnswerInfo.answerStatus == TalkfunAnswerStatusParticipated && self.model!.subjectExamineInfo.isEndOfTestPaper == false && indexPath.row == self.dataList.count - 1 && self.model!.subjectExamineInfo.pageType == TalkfunQuestionnairePageStatusOnePage)
        {
            unsubmitted = true
        }
        
        return unsubmitted
    }
    func questionTitle(count:NSInteger)
    {
        
        let countStr = NSString(format: "%i", count) as String
        
        let title = "答对" + countStr + "题"
        
        let font = UIFont(name: "PingFang SC", size: 14) as Any
        let attrString = NSMutableAttributedString(string: title)
      
        let attr: [NSAttributedString.Key : Any] = [.font: font,.foregroundColor: UIColor(red: 0.05, green: 0.73, blue: 0.25,alpha:1), ]
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
     
        self.headView.more.setAttributedTitle(attrString, for: UIControl.State.normal)
        
        let size: CGSize = title.size(withAttributes: [NSAttributedString.Key.font: font])
        self.addSubview(self.questionNumberCard)
        
        let moreX = 12.0
        let moreY = moreX
        let moreW = size.width + 22
        let moreH = 21.0
        self.headView.more.spacing = 2
        self.headView.more.frame = CGRect(x: moreX, y: moreY, width: moreW, height: moreH)
        
    }
    //点击上一页
    @objc func previousClick(btn:UIButton)
    {
        self.tailViewMoreTitle(next: false)
        self.turnPages()
    }
    //点击下一页
    @objc func nextClick(btn:UIButton)
    {
        let pageWidth = self.collectionView.frame.width
        let currentPage = NSInteger(self.collectionView.contentOffset.x / pageWidth )
        if (currentPage < self.questionNumberCard.list.count - 1) {
            self.tailViewMoreTitle(next: true)
            self.turnPages()
        }else
        {
            if (self.model!.subjectExamineInfo.isEndOfTestPaper == false) {
                self.submitAlert()
            }
        }
      
    }
    
    func turnPages()
    {
        self.tailView.nextBtn.colorView.isHidden = true
        
        self.tailView.previousBtn.setImage(UIImage.init(named: "HTLive.bundle/TFicon_Previous"), for: UIControl.State.normal)
        self.tailView.nextBtn.setImage(UIImage.init(named: "HTLive.bundle/TFicon_next"), for: UIControl.State.normal)
        
        let pageWidth = self.collectionView.frame.width
        let currentPage = NSInteger(self.collectionView.contentOffset.x / pageWidth )
        if (currentPage == 0) {
            
            if (self.questionNumberCard.list.count == 1 ) {
                self.tailView.previousBtn.setImage(UIImage.init(named: "HTLive.bundle/TFicon_Previous"), for: UIControl.State.normal)
                if (self.model!.subjectExamineInfo.isEndOfTestPaper == false) {
                    self.tailView.nextBtn.setImage(UIImage.init(named: "HTLive.bundle/"), for: UIControl.State.normal)
                    self.tailView.nextBtn.colorView.isHidden = false
                    self.tailView.nextBtn.setTitle("提交", for: UIControl.State.normal)
                    self.tailView.nextBtn.titleLabel!.font =  UIFont.PingFang(size: 14)
                    self.tailView.nextBtn.titleLabel?.textColor = UIColor(red: 1, green: 1, blue: 1,alpha:1)
                }
                
                
            }else
            {
                self.tailView.previousBtn.setImage(UIImage.init(named: "HTLive.bundle/TFicon_Previous"), for: UIControl.State.normal)
                self.tailView.nextBtn.setImage(UIImage.init(named: "HTLive.bundle/TFicon_next_Highlight"), for: UIControl.State.normal)

            }
            
        }else if (currentPage == self.questionNumberCard.list.count - 1  ) {
            
            self.tailView.previousBtn.setImage(UIImage.init(named: "HTLive.bundle/TFicon_Previous_Highlight"), for: UIControl.State.normal)
            
            if (self.model!.subjectExamineInfo.isEndOfTestPaper == false) {
                self.tailView.nextBtn.setImage(UIImage.init(named: "HTLive.bundle/"), for: UIControl.State.normal)
                self.tailView.nextBtn.colorView.isHidden = false
                self.tailView.nextBtn.setTitle("提交", for: UIControl.State.normal)
                self.tailView.nextBtn.titleLabel!.font =  UIFont.PingFang(size: 14)
                self.tailView.nextBtn.titleLabel?.textColor = UIColor(red: 1, green: 1, blue: 1,alpha:1)
            }
           
        }else
        {
            self.tailView.previousBtn.setImage(UIImage.init(named: "HTLive.bundle/TFicon_Previous_Highlight"), for: UIControl.State.normal)
            self.tailView.nextBtn.setImage(UIImage.init(named: "HTLive.bundle/TFicon_next_Highlight"), for: UIControl.State.normal)

        }

        
    }
    
    func tailViewMoreTitle(next:Bool)
    {
        let pageWidth = self.collectionView.frame.width as CGFloat
        let currentPage = NSInteger(self.collectionView.contentOffset.x / pageWidth )
        if (next) {
            if (currentPage < self.questionNumberCard.list.count - 1) {
                self.collectionView.contentOffset = CGPoint(x: (currentPage + 1) * Int(pageWidth) , y: 0)
            }
        }else
        {
            if (currentPage > 0 ) {
                self.collectionView.contentOffset = CGPoint(x: (currentPage - 1) * Int(pageWidth) , y: 0)
                
            }
            
        }
     
      
        let newPage = NSInteger(self.collectionView.contentOffset.x / pageWidth )

        
        self.tailViewMore(currentPage: newPage + 1)
    }
    
    func tailViewMore(currentPage:NSInteger)
    {
        self.currentPage = currentPage - 1
        let coutStr = NSString(format: "%i", currentPage  )
        
        let inx = coutStr as String + "/" + (NSString(format: "%i", self.questionNumberCard.list.count) as String)
        self.tailView.moreTitle(title: inx as NSString)
    }
    
    func headViewMore(currentPage:NSInteger)
    {
        let coutStr = NSString(format: "%i", currentPage  )
        
        let inx = coutStr as String + "/" + (NSString(format: "%i", self.questionNumberCard.list.count) as String)
        let status = self.model!.subjectExamineInfo.pageType as TalkfunQuestionnairePageStatus
        self.headView.moreTitle(title: inx as NSString,status:status )
    }
    @objc func headViewMoreClick(btn:UIButton)
    {
        //分页式 考试未结束   试卷未提交
        if((self.model) != nil && self.model!.subjectExamineInfo.pageType == TalkfunQuestionnairePageStatusPagination && self.model?.subjectExamineInfo.isEndOfTestPaper == false && self.model?.subjectExamineAnswerInfo.answerStatus == TalkfunAnswerStatusParticipated)
        {
            self.submitAlert()
            
        }else
        {
            //未提交
            if (self.model?.subjectExamineAnswerInfo.answerStatus == TalkfunAnswerStatusParticipated || self.model!.subjectExamineInfo.pageType == TalkfunQuestionnairePageStatusOnePage)
             {
               
                 self.tailViewMoreClick()
             }
        }
       
    }
    
    @objc func tailViewMoreClick()
    {

          
            UIView.animate(withDuration: 0.5, delay: 0.0, options: UIView.AnimationOptions.allowAnimatedContent) {
                self.questionNumberCard.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height)
            } completion: { Bool in
                
            }

    }
    @objc func closeOrBackClick(btn:UIButton)
    {
        self.timerInvalidate()

      // print("触发关闭窗口")
       self.closeOrBackUI()
   
    }
    
    @objc func closeOrBackUI()
    {
        
        UIView.animate(withDuration: 0.5, delay: 0.0, options: UIView.AnimationOptions.allowAnimatedContent) {
            self.YEqualsHigh = true
            self.frame = CGRect(x: self.frame.origin.x, y: self.frame.size.height, width: self.frame.size.width, height: self.frame.size.height)
        } completion: { Bool in
            self.tailView.isHidden = true
            self.cellSubmit.isHidden = true

        }
    }

    @objc func timerInvalidate() {
        if((self.headView.timer) != nil)
        {
            self.headView.timer.invalidate()
            self.headView.timer = nil
        }
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc func submitClick() {
        // 一页式2   未提交  考试未结束
        if((self.model) != nil && self.model!.subjectExamineInfo.pageType == TalkfunQuestionnairePageStatusOnePage && self.model?.subjectExamineInfo.isEndOfTestPaper == false && self.model?.subjectExamineAnswerInfo.answerStatus == TalkfunAnswerStatusParticipated)
        {
            self.submitAlert()
        }
        
    }
    
    func submitAlert()
    
    {
        
        /**随堂考*/
        if self.questionNumberCard.type == TFExaminationTypeTestPaper {
            // //是否填写好所有题目
            if(self.questionNumberCard.isCompleteTheAnswer() == true)
            {   //确定要提交吗？
                TalkfunAlertNewView.shareInstance(type:TalkfunAlertNewView.TalkfunAlertType.submit,target: self, action: #selector(self.sureButtonClick),ID:self.model!.subjectExamineInfo.id)
        
            }else{
                //你还有题目未做完,确定要提交吗?
                TalkfunAlertNewView.shareInstance(type:TalkfunAlertNewView.TalkfunAlertType.notCompletedButWantToSubmit,target: self, action: #selector(self.sureButtonClick),ID:self.model!.subjectExamineInfo.id)
              
            }
        }else
        {
            // //是否填写好所有必选题
            if(self.questionNumberCard.isListRequired() == true)
            {
                //确认提交吗
                TalkfunAlertNewView.shareInstance(type:TalkfunAlertNewView.TalkfunAlertType.submitToFill,target: self, action: #selector(self.sureButtonClick),ID:self.model!.subjectExamineInfo.id)
        
            }else{
                //你还有题目未做完,确定要提交吗?
                TalkfunAlertNewView.shareInstance(type:TalkfunAlertNewView.TalkfunAlertType.missingRequiredQuestions,target: self, action: #selector(self.sureButtonUI),ID:self.model!.subjectExamineInfo.id)
                
            }
        }
        
       
    }
    @objc func sureButtonUI(btn:UIButton) {
        btn.superview?.removeFromSuperview()
    }
   //确定
    @objc func sureButtonClick(btn:UIButton) {
        btn.superview?.removeFromSuperview()
         let access_key = self.model?.access.access_key
    
        if self.submitTestPaperBlock != nil {
            self.submitTestPaperBlock!( access_key! as NSString ,self.model!.subjectExamineInfo.id)
        }
    }
    func  getSuperviewIsEndOfTestPaper() ->Bool
    
    {
        let isEndOfTestPaper = (self.model?.subjectExamineInfo.isEndOfTestPaper)! as Bool
        
        return isEndOfTestPaper
    }
}
